import 'dart:convert';
import 'package:blurb/common/models/topic.dart';
import 'package:blurb/common/models/comment.dart';
import 'package:shared_preferences/shared_preferences.dart';

class TopicService {
  static const String _topicListKey = 'topic_list';
  static const String _topicCommentListKey = 'topic_comment_list';

  // 初始化默认话题和评论
  static Future<void> initDefaultTopicsAndComments() async {
    final prefs = await SharedPreferences.getInstance();
    final topicListStr = prefs.getString(_topicListKey);

    if (topicListStr == null) {
      final List<Topic> defaultTopics = [
        Topic(
          id: 1,
          title: 'The necessity of sun protection',
          description: 'Why is sun protection important for everyone?',
          userId: 1,
        ),
        Topic(
          id: 2,
          title: 'Best sunscreen for sensitive skin',
          description: 'Share your favorite sunscreen for sensitive skin.',
          userId: 2,
        ),
        Topic(
          id: 3,
          title: 'Physical vs Chemical sunscreen',
          description: 'Which do you prefer and why?',
          userId: 3,
        ),
        Topic(
          id: 4,
          title: 'How to reapply sunscreen outdoors',
          description:
              'Tips for reapplying sunscreen during outdoor activities.',
          userId: 4,
        ),
        Topic(
          id: 5,
          title: 'Kids and sun protection',
          description: 'How do you protect your children from the sun?',
          userId: 1,
        ),
      ];
      // 保存话题
      final List<Map<String, dynamic>> topicMapList = defaultTopics
          .map((topic) => topic.toJson())
          .toList();
      await prefs.setString(_topicListKey, jsonEncode(topicMapList));

      // 创建默认评论（每个话题评论数不同，最多的两个评论数最多）
      final DateTime now = DateTime.now();
      final List<Comment> defaultComments = [
        // Topic 1: 4条
        Comment(
          id: 1001,
          content: 'Sun protection is a must!',
          time: now.subtract(const Duration(hours: 5)).toIso8601String(),
          userId: 2,
          topicId: 1,
        ),
        Comment(
          id: 1002,
          content: 'I agree, it prevents aging.',
          time: now.subtract(const Duration(hours: 4)).toIso8601String(),
          userId: 3,
          topicId: 1,
        ),
        Comment(
          id: 1003,
          content: 'What SPF do you recommend?',
          time: now.subtract(const Duration(hours: 3)).toIso8601String(),
          userId: 4,
          topicId: 1,
        ),
        Comment(
          id: 1004,
          content: 'Don’t forget your neck!',
          time: now.subtract(const Duration(hours: 2)).toIso8601String(),
          userId: 1,
          topicId: 1,
        ),
        // Topic 2: 3条
        Comment(
          id: 1005,
          content: 'Sensitive skin needs mineral sunscreen.',
          time: now.subtract(const Duration(hours: 2)).toIso8601String(),
          userId: 1,
          topicId: 2,
        ),
        Comment(
          id: 1006,
          content: 'I use fragrance-free products.',
          time: now.subtract(const Duration(hours: 1)).toIso8601String(),
          userId: 3,
          topicId: 2,
        ),
        Comment(
          id: 1007,
          content: 'Patch test is important.',
          time: now.subtract(const Duration(minutes: 50)).toIso8601String(),
          userId: 4,
          topicId: 2,
        ),
        // Topic 3: 2条
        Comment(
          id: 1008,
          content: 'I prefer physical sunscreen.',
          time: now.subtract(const Duration(minutes: 40)).toIso8601String(),
          userId: 2,
          topicId: 3,
        ),
        Comment(
          id: 1009,
          content: 'Chemical sunscreen feels lighter.',
          time: now.subtract(const Duration(minutes: 30)).toIso8601String(),
          userId: 1,
          topicId: 3,
        ),
        // Topic 4: 5条（最多）
        Comment(
          id: 1010,
          content: 'I use spray for reapplication.',
          time: now.subtract(const Duration(minutes: 25)).toIso8601String(),
          userId: 2,
          topicId: 4,
        ),
        Comment(
          id: 1011,
          content: 'Powder sunscreen is convenient.',
          time: now.subtract(const Duration(minutes: 20)).toIso8601String(),
          userId: 3,
          topicId: 4,
        ),
        Comment(
          id: 1012,
          content: 'I carry a stick sunscreen.',
          time: now.subtract(const Duration(minutes: 15)).toIso8601String(),
          userId: 4,
          topicId: 4,
        ),
        Comment(
          id: 1013,
          content: 'Reapply every 2 hours!',
          time: now.subtract(const Duration(minutes: 10)).toIso8601String(),
          userId: 1,
          topicId: 4,
        ),
        Comment(
          id: 1014,
          content: 'Don’t forget ears and hands.',
          time: now.subtract(const Duration(minutes: 5)).toIso8601String(),
          userId: 2,
          topicId: 4,
        ),
        // Topic 5: 1条
        Comment(
          id: 1015,
          content: 'I use hats and long sleeves for my kids.',
          time: now.subtract(const Duration(minutes: 2)).toIso8601String(),
          userId: 3,
          topicId: 5,
        ),
      ];
      // 保存评论到topic_comment_list
      final List<Map<String, dynamic>> commentMapList = defaultComments
          .map((comment) => comment.toJson())
          .toList();
      await prefs.setString(_topicCommentListKey, jsonEncode(commentMapList));
    }
  }

  // 获取所有话题
  static Future<List<Topic>> getAllTopics() async {
    final prefs = await SharedPreferences.getInstance();
    final topicListStr = prefs.getString(_topicListKey);
    if (topicListStr != null) {
      final List<dynamic> topicMapList = jsonDecode(topicListStr);
      return topicMapList.map((topicMap) => Topic.fromJson(topicMap)).toList();
    }
    return [];
  }

  // 获取所有评论
  static Future<List<Comment>> getAllTopicComments() async {
    final prefs = await SharedPreferences.getInstance();
    final commentListStr = prefs.getString(_topicCommentListKey);
    if (commentListStr != null) {
      final List<dynamic> commentMapList = jsonDecode(commentListStr);
      return commentMapList
          .map((commentMap) => Comment.fromJson(commentMap))
          .toList();
    }
    return [];
  }

  // 获取指定话题的评论
  static Future<List<Comment>> getTopicComments(int topicId) async {
    final comments = await getAllTopicComments();
    return comments.where((c) => c.topicId == topicId).toList();
  }

  // 添加评论到指定话题
  static Future<void> addCommentToTopic(Comment comment) async {
    final prefs = await SharedPreferences.getInstance();
    final commentListStr = prefs.getString(_topicCommentListKey);
    List<Comment> comments = [];
    if (commentListStr != null) {
      final List<dynamic> commentMapList = jsonDecode(commentListStr);
      comments = commentMapList.map((c) => Comment.fromJson(c)).toList();
    }
    comments.add(comment);
    final List<Map<String, dynamic>> commentMapList = comments.map((c) => c.toJson()).toList();
    await prefs.setString(_topicCommentListKey, jsonEncode(commentMapList));
  }

  // 添加新话题
  static Future<void> addTopic(Topic topic) async {
    final prefs = await SharedPreferences.getInstance();
    final topicListStr = prefs.getString(_topicListKey);
    List<Topic> topics = [];
    if (topicListStr != null) {
      final List<dynamic> topicMapList = jsonDecode(topicListStr);
      topics = topicMapList.map((t) => Topic.fromJson(t)).toList();
    }
    topics.add(topic);
    final List<Map<String, dynamic>> topicMapList = topics.map((t) => t.toJson()).toList();
    await prefs.setString(_topicListKey, jsonEncode(topicMapList));
  }

  // 获取热门话题（评论数最多的2个）
  static Future<List<Topic>> getHotTopics() async {
    final topics = await getAllTopics();
    final comments = await getAllTopicComments();
    // 统计每个话题的评论数
    final Map<int, int> topicCommentCount = {};
    for (final c in comments) {
      if (c.topicId != null) {
        topicCommentCount[c.topicId!] =
            (topicCommentCount[c.topicId!] ?? 0) + 1;
      }
    }
    // 按评论数排序，取前2
    final hotTopicIds = topicCommentCount.entries.toList()
      ..sort((a, b) => b.value.compareTo(a.value));
    final top2Ids = hotTopicIds.take(2).map((e) => e.key).toSet();
    return topics.where((t) => top2Ids.contains(t.id)).toList();
  }

  // 添加、删除、更新话题（略，可按需补充）
}
